from lxml import etree


html_str = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    <li class="id1"><a href="https://www.baidu.com">百度</a></li>
    <li class="id2"><a href="https://www.jd.com">京东</a></li>
    <li class="id3"><a href="https://www.taobao.com">淘宝</a></li>
</ul>

<h2><a href="https://www.taobao.com">淘宝</a></h2>
</body>
</html>
"""

tree = etree.HTML(html_str)
# cssselect 需要安装相应的包
# print(tree.cssselect('a'))
# print(tree.cssselect('a')[0].text)
# print(tree.cssselect('a')[0].get('href'))


# 路径
# 根路径
# print(tree.xpath('/html'))

# 子路径
# print(tree.xpath('body/ul/li/a'))

# 任意子路径
# print(tree.xpath('//a'))

# 当前路径 | 父路径
# ul = tree.xpath('//ul')[0]
# print(ul.xpath('./li/a'))
# print(ul.xpath('../h2'))

# 属性
# print(tree.xpath('//li[@class="id1"]/a'))
# print(tree.xpath('//li[@class="id1"]/a/text()'))
# print(tree.xpath('//li[@class="id1"]/a/@href'))

#
print(tree.xpath('//li[contains(@class, "id")]/a'))
print(tree.xpath('//li[contains(@class, "id")]/a/text()'))
print(tree.xpath('//li[contains(@class, "id")]/a/@href'))
# starts-with()	以...开始
# [position()]	按位置选择 可以添加and/or 判断条件
